/*
    Copyright 2011 Anishek Agarwal(anishek@gmail.com), Ashish Mishra(ashish@ashishmishra.in)
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

package com.thoughtworks.ant;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class VelocityMacroValidator {
    private File dir;
    private String velocityMacroSuffix;

    private static final Pattern macroDefitionPattern;
    private static final Pattern macroCallPattern;

    private static final String DEFAULT_VELOCITY_FILE_SUFFIX = ".vm";

    static {
        macroDefitionPattern = Pattern.compile("#macro\\s*\\(\\s*(.*?)(\\s|\\))");
        macroCallPattern = Pattern.compile("#(.*?)(\\s|\\()");
    }

    public VelocityMacroValidator(String dir) {
        this(dir, DEFAULT_VELOCITY_FILE_SUFFIX);
    }

    public VelocityMacroValidator(String dirPath, String velocityMacroSuffix) {
        File dir = new File(dirPath);
        if (!dir.isDirectory())
            throw new IllegalArgumentException(dirPath + "  is not a directory");
        this.dir = dir;
        this.velocityMacroSuffix = (null == velocityMacroSuffix || "".equals(velocityMacroSuffix.trim()) ? DEFAULT_VELOCITY_FILE_SUFFIX : velocityMacroSuffix.trim());
    }

    public void pouplateMacros(Set<String> macroDefinitions, Set<String> macroCalls) throws IOException {
        processFiles(macroDefinitions, macroCalls);
        processDirectories(macroDefinitions, macroCalls);
    }

    private void processDirectories(Set<String> macroDefinitions, Set<String> macroCalls) throws IOException {
        List<File> directoryList = listDirectories();
        for (File dir : directoryList) {
            new VelocityMacroValidator(dir.getPath(), velocityMacroSuffix).pouplateMacros(macroDefinitions, macroCalls);
        }
    }

    private void processFiles(Set<String> macroDefinitions, Set<String> macroCalls) throws IOException {
        List<File> filesInDirectory = listFiles();
        for (File file : filesInDirectory) {
            String fileContents = readFile(file);
            macroDefinitions.addAll(macroDefitions(fileContents));
            macroCalls.addAll(macroCalls(fileContents));
        }
    }

    Set<String> macroCalls(String fileContents) {
        Set<String> macroCalls = new HashSet<String>();
        Matcher matcher = macroCallPattern.matcher(fileContents);
        while (matcher.find()) {
            String matchedString = matcher.group(1);
            if (matchedString.equals("macro")) continue;
            macroCalls.add(matchedString);
        }
        return macroCalls;
    }

    Set<String> macroDefitions(String fileContents) {
        Set<String> macroDefinitions = new HashSet<String>();
        Matcher matcher = macroDefitionPattern.matcher(fileContents);
        while (matcher.find()) {
            macroDefinitions.add(matcher.group(1));
        }
        return macroDefinitions;
    }

    String readFile(File file) throws IOException {
        byte[] bytesRead = new byte[4096];
        FileInputStream stream = new FileInputStream(file);
        StringWriter writer = new StringWriter();
        for (int numberOfBytesRead = stream.read(bytesRead); numberOfBytesRead != -1; numberOfBytesRead = stream.read(bytesRead)) {
            writer.append(new String(bytesRead, 0, numberOfBytesRead));
        }
        return writer.toString();
    }

    private List<File> listDirectories() {
        return Arrays.asList(dir.listFiles(new DirectoryFilter()));
    }

    private List<File> listFiles() {
        return Arrays.asList(dir.listFiles(new SuffixFileFilter(velocityMacroSuffix)));
    }
}
